<template>
  <div class="work-catalog">
    <div class="header-group">
      <div class="work-title">
        <span><el-button size="small" type="success" :loading="syncloading" @click="handleSynchronous">同步数据</el-button></span>
        <span><el-button size="small" @click="handleCommand({type:1})">增加目录</el-button></span>
      </div>
      <div class="search-input">
        <el-input placeholder="检索作业、图纸、零件、排版" v-model="keyword" class="input-with-select">
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </div>
      <div class="select-group">
        <div class="select-row">
          <el-date-picker style="width:100%;" value-format="yyyy-MM-dd HH:mm:ss" v-model="times" type="datetimerange" :picker-options="pickerOptions" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" align="right">
          </el-date-picker>
        </div>
        <div class="select-row">
          <el-select style="width:100%;" v-model="status" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
    </div>
    <div class="tree-group scrollbar" v-loading="loading">
      <el-tree :props="{label:'name'}" ref="tree" :data="treeData" :default-checked-keys="checkeds" show-checkbox node-key="id" default-expand-all :expand-on-click-node="false" @check="treeChage">
        <span class="add-span" slot-scope="{ node, data }">
          <span class="tree-left">
            <img class="tree-img" v-if="data.nodeType === 0" :src="files" />
            <img class="tree-img" v-else :src="file" />
            <overflow-text :tooltip-content="node.label"></overflow-text>
            <!-- <span class="tree-title">{{ node.label }}</span> -->
          </span>
          <span>
            <el-dropdown trigger="click" @command="handleCommand">
              <span class="tree-more el-icon-more"></span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{type:2,data}" v-if="data.nodeType === 0">添加目录</el-dropdown-item>
                <el-dropdown-item :command="{type:3,data}" v-if="data.nodeType === 0">添加作业</el-dropdown-item>
                <el-dropdown-item :command="{type:4,data}">编辑</el-dropdown-item>
                <el-dropdown-item :command="{type:5,data}">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
        </span>
      </el-tree>
    </div>

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false" top="1.5%">
      <div v-loading="dialogLoading">
        <el-form ref="form" :model="form" :rules="rules" label-width="110px" label-position="left">
          <el-form-item label="目录名称" prop="name">
            <el-input v-model.trim="form.name" placeholder="请输入目录名称" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" v-debounce-click="submitForm">确 定</el-button>
          <el-button @click="open=false">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog :title="worktitle" :visible.sync="openwork" width="600px" append-to-body :close-on-click-modal="false" top="1.5%">
      <div v-loading="dialogworkLoading">
        <el-form ref="workform" :model="formwork" :rules="ruleswork" label-width="110px" label-position="left">
          <el-form-item label="作业名称" prop="name">
            <el-input v-model.trim="formwork.name" placeholder="请输入作业名称" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" v-debounce-click="submitWorkForm">确 定</el-button>
          <el-button @click="openwork=false">取 消</el-button>
        </div>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import file from '@/assets/img/file_icon.png';
import files from '@/assets/img/files_icon.png';
import moment from 'moment';
import { isString } from 'lodash';
import { mapState } from 'vuex';
import { v4 as uuidv4 } from 'uuid';
import OverflowText from '@/components/overflowText/OverflowText.vue';
export default {
  components:{OverflowText},
  name: 'Workcatalog',
  props: {
    imgUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      file: file,
      files: files,
      messageList: [],
      times: [],
      status: '',
      options: [{
        value: '1',
        label: '全部'
      }, {
        value: '2',
        label: '已完成'
      }, {
        value: '3',
        label: '未完成'
      }],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      treeData: [],
      checkeds: [],
      keyword: '',
      dialogLoading: false,
      deviceList: [],
      open: false,
      title: '新增目录',
      form: {
        name: '',//信息名称
      },
      // 表单校验   
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ]
      },
      worktitle: '新增作业',
      openwork: false,
      dialogworkLoading: false,
      formwork: {
        name: "",//作业名称
      },
      ruleswork: {
        name: [
          { required: true, message: "作业名称不能为空", trigger: "blur" },
        ]
      },
      loading: false,
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.app.userInfo,
      checkTaskIds: (state) => state.app.checkTaskIds,
      processType: state => state.app.processType,
      syncloading: state => state.resource.syncloading,
      syncRefreshCode: state => state.resource.syncRefreshCode,
    }),
  },
  watch: {
    imgUrl: function (val, oldVal) {
      if (val != oldVal) {
        this.imgModelUrl = val;
      }
    },
    processType:{
      deep:true,
      handler:function(val,old){
        if(val!=old){
          this.$store.dispatch('app/setCheckTasks', []);
          this.$store.dispatch('app/setCheckTaskIds', []);
          this.checkeds=[];
          this.initAjaxMethod();
        }
      }
    },
    syncRefreshCode:{
      deep:true,
      handler:function(val,old){
        if(val!=old){
          this.initAjaxMethod();
        }
      }
    },
  },
  created() {
    if (this.checkTaskIds && this.checkTaskIds.length > 0) {
      this.checkeds = this.checkTaskIds;
    }
    this.initAjaxMethod();
    // console.log('uuidv4()',uuidv4())
  },
  methods: {
    initAjaxMethod() {
      this.loading = true;
      this.$http
        .get(this.$API.WORK_CALALOG)
        .then((res) => {
          this.loading = false;
          let list = Array.isArray(res.data) ? res.data : [];
          const traverseTree = (node) => {
            if (node) {
              node.disabled = node.nodeType == 0 ? true : false;
              if (node.children) {
                node.children.forEach(traverseTree);
              }
            }
          }
          list.forEach(traverseTree);
          this.treeData = list;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    handleCommand(command) {
      let type = command && command.type ? Number(command.type) : 0;
      this.dialogLoading = false;
      this.dialogworkLoading = false;
      if (type === 1) {
        this.resetMetod(null, 1);
      } else if (type === 2) {
        this.resetMetod(command.data, 2);
      } else if (type === 3) {
        this.resetWorkMetod(command.data, 1)
      } else if (type === 4) {
        if (command.data.nodeType === 0) {
          this.resetMetod(command.data, 3);
        } else {
          this.resetWorkMetod(command.data, 2)
        }
      } else if (type === 5) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.remove(command.data.id, command.data.nodeType)
        });
      }
    },

    remove(id, type) {
      this.loading = true;
      let path = type === 0 ? this.$API.WORK_CALALOG_BATH : this.$API.WORK_TASK;
      this.$http
        .del(path + '/' + id)
        .then((res) => {
          this.loading = false;
          this.$message.success('操作成功');
          this.initAjaxMethod();
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    resetMetod(row = null, flag = 1) {
      let form = {};
      // 新增一级目录
      if (flag === 1) {
        form.name = '';
        this.title = "添加目录";
      } else if (flag === 2) {
        // 新增二级目录
        form.name = '';
        form.parentId = row.id;
        this.title = "修改目录";
      } else if (flag === 3) {
        // 修改目录
        form.name = row ? row.name : '';
        form.id = row.id;
        this.title = "修改目录";
      }
      console.log('form', form);
      this.form = form;
      this.open = true;
      this.$nextTick(() => {
        this.$refs['form'].clearValidate();
        this.dialogLoading = false;
      })
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.dialogLoading = true;
          if (isString(this.form.id)) {
            this.$http.put(this.$API.WORK_CALALOG_BATH + '/' + this.form.id, this.form, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('修改成功');
              this.open = false;
              this.dialogLoading = false;
              this.initAjaxMethod();
            })
          } else {
            let addParmes = this.form;
            addParmes.id = uuidv4();
            this.$http.post(this.$API.WORK_CALALOG_BATH, addParmes, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('添加成功');
              this.open = false;
              this.dialogLoading = false;
              this.initAjaxMethod();
            })
          }

        }
      });
    },
    submitWorkForm() {
      this.$refs["workform"].validate((valid) => {
        if (valid) {
          this.dialogworkLoading = true;
          if (this.formwork.id) {
            this.$http.put(this.$API.WORK_TASK + '/' + this.form.id, this.formwork, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('修改成功');
              this.openwork = false;
              this.dialogworkLoading = false;
              this.initAjaxMethod();
            })
          } else {
            let addParmes = this.formwork;
            addParmes.id = uuidv4();
            this.$http.post(this.$API.WORK_TASK, addParmes, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('添加成功');
              this.openwork = false;
              this.dialogworkLoading = false;
              this.initAjaxMethod();
            })
          }

        }
      });
    },
    resetWorkMetod(row = null, flag) {
      let formwork = {};
      // 新增作业
      if (flag === 1) {
        formwork.name = '';
        formwork.catalogId = row.id;
        formwork.userId = this.userInfo.id;
        formwork.remark = 'string';
        formwork.needDate = moment().format();
        formwork.processType = 1;
        formwork.companyId = this.userInfo.company.id;
        this.worktitle = '新增作业';
      } else if (flag === 2) {
        // 编辑作业
        formwork.name = row ? row.name : '';
        formwork.remark = "string";
        formwork.state = 0;
        formwork.id = row.id;
        this.worktitle = '编辑作业';
      }
      console.log('formwork', formwork);
      this.formwork = formwork;
      this.openwork = true;
      this.$nextTick(() => {
        this.$refs['workform'].clearValidate()
      })
    },
    treeChage() {
      const checkedNodes = this.$refs.tree.getCheckedNodes();
      let checkTaskIds = checkedNodes.filter(item => item.nodeType === 1);
      this.$store.dispatch('app/setCheckTasks', checkTaskIds)
      this.$store.dispatch('app/setCheckTaskIds', checkTaskIds.map(o => o.id))
    },
    async handleSynchronous(){
        return this.$store.dispatch('resource/handleSynchronous')
    }
  }
};
</script>
<style lang="less">
.work-catalog {
  background: #fafafa;
  box-shadow: 1px 1px 4px -3px #000;
  height: 94vh;
  padding: 10px 10px 10px 0;
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .header-group {
    .work-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 12px;
      color: #000;
    }
    .search-input {
      padding: 10px 0;
    }
  }
  .el-tree-node__content {
    span {
      font-size: 12px;
    }
  }
  .add-span {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .tree-left {
      width: 80%;
      display: flex;
      align-items: center;
      .tree-img {
        height: 16px;
        width: auto;
      }
      .tree-title {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        font-size: 12px;
        color: #333;
        padding-left: 4px;
      }
    }
    .tree-more {
      font-size: 14px;
      color: #333;
      width: 26px;
      height: 20px;
      background: #eee;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .el-tree-node__content .el-checkbox__input.is-disabled {
    display: none;
  }
  .select-group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 10px;
    .select-row {
      width: 49%;
    }
  }
  .tree-group {
    height: 78vh;
  }
}
</style>
